package user

import (
	"context"
	"github.com/zeromicro/go-zero/core/logx"
	"private-domain-overseas-service/app/business/api/internal/svc"
	"private-domain-overseas-service/tools/ent"
	"private-domain-overseas-service/tools/ent/hzusersurvey"
	"private-domain-overseas-service/tools/ent/predicate"
)

type UserSurveyDao struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUserSurveyDao(ctx context.Context, svcCtx *svc.ServiceContext) *UserSurveyDao {
	return &UserSurveyDao{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

// UserSurveyCreate - 创建用户问卷
func (l *UserSurveyDao) UserSurveyCreate(userSurvey *ent.HzUserSurvey, tx *ent.Tx) error {
	clientDao := l.svcCtx.Orm.HzUserSurvey
	if tx != nil {
		clientDao = tx.HzUserSurvey
	}
	err := clientDao.Create().
		SetUserSurveyPhone(userSurvey.UserSurveyPhone).
		SetUserSurveyName(userSurvey.UserSurveyName).
		SetUserSurveySex(userSurvey.UserSurveySex).
		SetUserSurveyType(userSurvey.UserSurveyType).
		SetUserSurveyOrderNum(userSurvey.UserSurveyOrderNum).
		SetCreatedAt(userSurvey.CreatedAt).
		SetUpdateAt(userSurvey.UpdateAt).
		Exec(l.ctx)
	if err != nil {
		return err
	}
	return nil
}

// UserSurveyConditionsAll - 根据条件查询多个用户问卷信息
func (l *UserSurveyDao) UserSurveyConditionsAll(conditions []predicate.HzUserSurvey, limit int64) ([]*ent.HzUserSurvey, error) {
	version, err := l.svcCtx.Orm.HzUserSurvey.Query().
		Where(conditions...).
		Order(ent.Desc(hzusersurvey.FieldID)).
		Limit(int(limit)).
		All(l.ctx)
	if err != nil {
		return nil, err
	}
	return version, nil
}

// UserSurveyUpdate - 编辑用户问卷
func (l *UserSurveyDao) UserSurveyUpdate(userSurvey *ent.HzUserSurvey, tx *ent.Tx) error {
	clientDao := l.svcCtx.Orm.HzUserSurvey
	if tx != nil {
		clientDao = tx.HzUserSurvey
	}
	err := clientDao.UpdateOneID(userSurvey.ID).
		SetUserSurveyOrderNum(userSurvey.UserSurveyOrderNum).
		SetUpdateAt(userSurvey.UpdateAt).
		Exec(l.ctx)
	if err != nil {
		return err
	}
	return nil
}

// UserSurveyConditionsFirst - 根据条件查询单条用户问卷
func (l *UserSurveyDao) UserSurveyConditionsFirst(conditions []predicate.HzUserSurvey) (*ent.HzUserSurvey, error) {
	survey, err := l.svcCtx.Orm.HzUserSurvey.Query().
		Where(conditions...).
		First(l.ctx)
	if err != nil {
		return nil, err
	}
	return survey, nil
}
